/*******************************************************************************
 * Copyright (c) 2011 Olexandr V. Shaposhnikov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Olexandr V. Shaposhnikov - initial API and implementation and/or initial documentation
 *******************************************************************************/
package com.funkyroach.use.plugin;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.Status;
import org.eclipse.dltk.core.IShutdownListener;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import com.funkyroach.use.ui.text.USTextTools;

public class USPlugin extends AbstractUIPlugin {

	public static final String PLUGIN_ID = "com.funkyroach.use"; // NON-NLS-1
	private final ListenerList shutdownListeners = new ListenerList();

	private static USPlugin s_Instance;
	private static USTextTools s_textTools = null;

	public void start(BundleContext context) throws Exception {
		super.start(context);
		s_Instance = this;
	}

	public static USPlugin instance() {
		return s_Instance;
	}

	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}

	public static IWorkspace getWorkspace() {
		return ResourcesPlugin.getWorkspace();
	}

	public static void log(IStatus status) {
		USPlugin in = instance();
		if (in != null) {
			in.getLog().log(status);
		}
	}

	public static void log(Throwable e) {
		log(new Status(IStatus.ERROR, PLUGIN_ID, "internal error", e));
	}

	public USTextTools getTextTools() {
		if (s_textTools == null) {
			s_textTools = new USTextTools(true);
		}
		return s_textTools;
	}

	public void addShutdownListener(IShutdownListener listener) {
		shutdownListeners.add(listener);
	}

	public void stop(BundleContext context) throws Exception {
		try {
			Object[] listeners = shutdownListeners.getListeners();
			for (int i = 0; i < listeners.length; ++i) {
				((IShutdownListener) listeners[i]).shutdown();
			}
			shutdownListeners.clear();
			s_Instance = null;
		} finally {
			super.stop(context);
		}
	}

}
